#pragma once
#include<iostream>
#include<string>
#include<pthread.h>
#include<functional>


namespace ThreadModle
{

    using func_t=std::function<void(std::string&)>;//类似typedef
    //typedef void(*func_t)(ThreadDate *td);

    class Thread
    {
    public:
        void Excute()
        {
            _isrunning=true;
            _func(_name);
            _isrunning=false;
        }
    public:
        Thread(const std::string &name ,func_t func)
        :_name(name),
        _func(func)
        {}
        static void *ThreadRoutine(void *args)//静态为了去掉隐藏的this指针
        {
            Thread *self=static_cast<Thread*>(args);
            self->Excute();
            return (void*)0;
        }
        bool Start()
        {
            int n=::pthread_create(&_tid ,nullptr ,ThreadRoutine,this);//::代表使用标准库中的
            if(n!=0)return false;
            return true;
        }
        std::string status()
        {
            if(_isrunning)return "running";
            else return "sleep";
        }
        void Stop()
        {
            if(_isrunning)
            {
                _isrunning=false;
                ::pthread_cancel(_tid);
            }
        }
        void Join()
        {
            ::pthread_join(_tid,nullptr);
        }
        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {
            Join();
            Stop();
        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;
    };
}